<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    /*
  将数组的值先克隆一份并排序
比较新数组和原数组的值，找出不同元素出现的开始位置和结束位置
两者距离就是我们要的结果
    */
    var findUnsortedSubarray = function (nums) {
      let snums = nums.slice();
      snums.sort((a, b) => a - b);
      let start = nums.length, end = 0;
      for (let i = 0; i < nums.length; i++) {
        if (snums[i] !== nums[i]) {
          start = Math.min(start, i);
          end = Math.max(end, i);
        }
      }
      return end - start > 0 ? end - start + 1 : 0;
    };
    console.log(findUnsortedSubarray(nums = [1, 2, 3, 4]))
  </script>
</body>

</html>